﻿using System;
using System.Collections.Generic;

namespace ProblemsSet
{
    public class Problem_66 : BaseProblem
    {
        public override object GetResult()
        {
            const int max = 1000;

            var res = "0";
            long maxD = 0;

            for (long d = 2; d <= max; d++)
            {
                long cnt = 0;
                var fracs = MathLogic.GetContinuedFractions(d, out cnt);
                if (cnt == 0) continue;
                var nom = "";
                var denom = "";
                long cntt = 0;
                while (true)
                {
                    cntt++;
                    MathLogic.GetDivideByFractions(fracs, out nom, out denom, cntt);
                    var y2 = MathLogic.MultipleString(denom, denom);// MathLogic.MultipleString(denom, Convert.ToInt64(denom));
                    var x2 = MathLogic.MultipleString(nom, nom);// MathLogic.MultipleString(nom, Convert.ToInt64(nom));
                    if (MathLogic.SummString("1", MathLogic.MultipleString(y2, d)) == x2)
                    {
                        if (MathLogic.IsGreat(nom, res))
                        {
                            res = nom;
                            maxD = d;
                        }
                        break;
                    }
                }
            }
            return maxD;
        }

        public override string Problem
        {
            get
            {
                return @"Consider quadratic Diophantine equations of the form:

x2 – Dy2 = 1

For example, when D=13, the minimal solution in x is 6492 – 131802 = 1.

It can be assumed that there are no solutions in positive integers when D is square.

By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we obtain the following:

32 – 222 = 1
22 – 312 = 1
92 – 542 = 1
52 – 622 = 1
82 – 732 = 1

Hence, by considering minimal solutions in x for D  7, the largest x is obtained when D=5.

Find the value of D  1000 in minimal solutions of x for which the largest value of x is obtained.";
            }
        }

        public override bool IsSolved
        {
            get
            {
                return true;
            }
        }

        public override object Answer
        {
            get
            {
                return 661;
            }
        }

    }
}
